package org.crazyit.cloud;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.ZoneAwareLoadBalancer;

@RestController
@Configuration
public class TestController {
	
	@Bean
	@LoadBalanced
	public RestTemplate getRestTemplate() {
		return new RestTemplate();
	}

	@RequestMapping(value="/router")
	@ResponseBody
	public String router() {
		RestTemplate tpl = getRestTemplate();
		String json = tpl.getForObject("http://spring-lb-provider/call/1", String.class);		
		return json;
	}
	
	@Autowired
	private LoadBalancerClient client;
	
	@RequestMapping(value="/lb",method=RequestMethod.GET,
			produces=MediaType.APPLICATION_JSON_VALUE)
	public ServiceInstance lb() {
		ServiceInstance choose = client.choose("spring-lb-provider");
		return choose;
	}
	
	@Autowired
	private SpringClientFactory factory;
	
	@RequestMapping(value="/fa",method=RequestMethod.GET)
	public String factory() {
		ILoadBalancer lb = factory.getLoadBalancer("default");
		System.out.println(lb.getClass().getName());
		
		ZoneAwareLoadBalancer lb2 = (ZoneAwareLoadBalancer)factory.getLoadBalancer("spring-lb-provider");
		System.out.println(lb2.getRule().getClass().getName());
		return "";
	}
	
}




































